package top.shiyiri.java;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author Aunean
 * @date 2022/1/10
 */
/*
UDP协议的网络编程

 */
public class UDPTest {

    //发送端
    @Test
    public void sender() {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();

            byte[] data = "UDP发送信息的方式".getBytes();

            InetAddress localHost = InetAddress.getLocalHost();
            DatagramPacket packet = new DatagramPacket(data, 0, data.length, localHost, 9020);

            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            assert socket != null;
            socket.close();
        }
    }

    //接收端
    @Test
    public void receiver() {

        DatagramSocket socket = null;
        DatagramPacket packet = null;
        try {
            socket = new DatagramSocket(9020);
            byte[] buffer = new byte[1024];
            packet = new DatagramPacket(buffer, 0, buffer.length);

            socket.receive(packet);

            System.out.println(new String(packet.getData(), 0, packet.getLength()));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            assert socket != null;
            socket.close();
        }
    }
}
